//
//  GXCycleImages.m
//  16-UICollectionViewCycleImage
//
//  Created by 曹曹 on 16/8/4.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "GXCycleImages.h"
#import "UIImageView+WebCache.h"

#define kCollectionViewCellReuse @"cellReuse"
#define kArc4RandomColor [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:1]

@interface GXCycleImages () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation GXCycleImages

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}
// SB中创建控件时走下边的方法(读取本地SB,xib等文件)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    [self createCollectionView];
    [self createPageControl];
    [self addTimer];
}

- (void)createCollectionView {
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    _collectionView.pagingEnabled = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_collectionView];
    [_collectionView registerClass:[GXCycleImagesCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];
}

- (void)createPageControl {
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:0.11 green:0.69 blue:0.56 alpha:1.00];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    [self addSubview:_pageControl];
}
#pragma mark - 代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    _pageControl.numberOfPages = _imagesArray.count - 2;
    return _imagesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GXCycleImagesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", _imagesArray[indexPath.row]]]
                      placeholderImage:[UIImage imageNamed:_placeholder]];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.indexPath(indexPath);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _flowLayout.itemSize = self.bounds.size;
    _collectionView.frame = self.bounds;
    [_collectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    _pageControl.frame = CGRectMake(0, 0, 100, 20);
    _pageControl.center = CGPointMake(CGRectGetWidth(self.bounds) / 2, CGRectGetHeight(self.bounds) - 10);
    [_pageControl addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventValueChanged];
}

- (void)changeImage:(UIPageControl *)pageControl {
    _collectionView.contentOffset = CGPointMake(CGRectGetWidth(self.bounds) * (_pageControl.currentPage + 1), 0);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x <= _collectionView.bounds.size.width / 2.0) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_imagesArray.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x >= _collectionView.bounds.size.width * (_imagesArray.count - 1)) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    NSInteger page = _collectionView.contentOffset.x / self.bounds.size.width;
    _pageControl.currentPage = page - 1;
}

- (void)setImagesArray:(NSMutableArray *)imagesArray {
    _imagesArray = [self imageArrayWithArray:imagesArray];
}

- (__kindof NSArray *)imageArrayWithArray:(NSArray *)array {
    NSMutableArray *imageArray = [NSMutableArray arrayWithArray:array];
    NSString *first = array.firstObject;
    NSString *lasst = array.lastObject;
    [imageArray addObject:first];
    [imageArray insertObject:lasst atIndex:0];
    [_collectionView reloadData];
    return imageArray;
}

- (void)addTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(xchImage:) userInfo:nil repeats:YES];
    _timer = timer;
}

- (void)removeTimer {
    [self.timer invalidate];
    _timer = nil;
}

- (void)xchImage:(NSTimer *)timer {
    CGFloat totaloffset = _collectionView.contentOffset.x + self.bounds.size.width;
    [_collectionView setContentOffset:CGPointMake(totaloffset, 0) animated:YES];
    if (totaloffset == (_imagesArray.count - 1) * self.bounds.size.width) {
        _collectionView.contentOffset = CGPointZero;
    }
    _pageControl.currentPage = (_collectionView.contentOffset.x + self.bounds.size.width) / self.bounds.size.width - 1;
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addTimer];
}

@end

/**
 GXCycleImagesCell
 */
@implementation GXCycleImagesCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.userInteractionEnabled = YES;
        [self.contentView addSubview:_imageView];
    }
    return self;
}

@end
